<?php

namespace app\adminapi\service;

use app\adminapi\model\sysuser\SysUserRoleDO;
use app\common\exception\OtherException;

class SysUserRoleService
{
    public function getSysUserRole(int $userId)
    {
        $this->validSysUserRoleExist($userId);
        $where[] = ['user_id', '=', $userId];
        return (new SysUserRoleDO())->where($where)->find();
    }

    public function deleteUserRoleByUserId(int $userId)
    {
        return SysUserRoleDO::destroy(['user_id'=>$userId]);
    }

    public function addSysUserRole(array $sysUserRoleDO)
    {
        $this->deleteUserRoleByUserId($sysUserRoleDO['userId']);
        return SysUserRoleDO::create($sysUserRoleDO);
    }

    private function validSysUserRoleExist(int $userId)
    {
        $where[] = ['user_id', '=', $userId];
        $exist = (new SysUserRoleDO())->where('user_id', $userId)->find();
        if (empty($exist)) {
            throw new OtherException('用户尚未分配权限');
        }
    }
}